package com.shoprh.system.handlers;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.shoprh.common.utils.StringUtils;
import com.shoprh.system.service.ICurrentUserService;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Slf4j
@Component
public class MyTenantLineHandler implements TenantLineHandler {

    /**
     * 排除过滤的表
     */
    private static final String[] tableList = {"tables", "columns", "rh_product_category_store", "rh_article_article_tag", "rh_shipping_method_payment_method",
            "rh_product_product_tag", "rh_product_promotion", "rh_product_store_product_tag", "rh_area"};

    /**
     * 排除过滤的表前缀
     */
    private static final String[] tablePrefix = {"qrtz", "sys", "gen"};

    @Autowired
    private ICurrentUserService userOnlineService;

    /**
     * 返回当前用户的租户ID
     */
    @Override
    public Expression getTenantId() {
        // 取出当前请求的服务商ID，通过解析器注入到SQL中。
        Long tenantId = userOnlineService.getTenantId();
//        log.debug("当前租户为:{}", tenantId);
        if (tenantId == null) {
            return new NullValue();
        }
        return new LongValue(tenantId);
    }

    /**
     * 跳过不需要加多租户的表
     */
    @Override
    public boolean ignoreTable(String tableName) {
        String prefix = StringUtils.substringBefore(tableName, "_");
        if (Arrays.asList(tableList).contains(tableName) || Arrays.asList(tablePrefix).contains(prefix)) {
            return true;
        }
        return false;
    }

}
